import { createStore } from 'redux'
const initState = {
  todos: [{
    id: 1,
    text: 'item-1',
    completed: true
  },{
    id: 2,
    text: 'item-2',
    completed: true
  },{
    id: 3,
    text: 'item-3',
    completed: false
  },{
    id: 4,
    text: 'item-4',
    completed: false
  }], 
  count: 1
}

// 处理reducer 
// 默认会执行一次
// 当每次 dispatch 分发 action 都会执行
// 应该进入对应的条件分支语句
// 必须有 return 数据
const reducer = (state = initState, action) => {
  const { todos, count } = state
  switch(action.type) {
    case 'add':
      return {
        ...state,
        count: count + 1
      };
    case 'change': 
      return {
        ...state,
        todos: todos.map(item => {
          if(item.id === action.id) {
            return {
              ...item,
              completed: !item.completed
            }
          }
          return item
        })
      };
    case "del": 
      return {
        ...state,
        todos: todos.filter(item => item.id !== action.id)
      };
    default: 
      // return state
  }
}

// 抛出仓库
const store = createStore(reducer)


export default store